/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package qs.crm.service.impl;

import lombok.RequiredArgsConstructor;
import qs.crm.domain.EmailConfig;
import qs.crm.domain.vo.EmailVo;
import qs.crm.exception.BadRequestException;
import qs.crm.repository.EmailRepository;
import qs.crm.service.EmailService;
import qs.crm.utils.EncryptUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;
import java.util.Optional;

/**
 * @author 251291
 * @date 2018-12-26
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "email")
public class EmailServiceImpl implements EmailService {
    private final EmailRepository emailRepository;
    private final JavaMailSender javaMailSender;
    @Override
    @CachePut(key = "'config'")
    @Transactional(rollbackFor = Exception.class)
    public EmailConfig config(EmailConfig emailConfig, EmailConfig old) throws Exception {
        emailConfig.setId(1L);
        if(!emailConfig.getPass().equals(old.getPass())){
            // 对称加密
            emailConfig.setPass(EncryptUtils.desEncrypt(emailConfig.getPass()));
        }
        return emailRepository.save(emailConfig);
    }

    @Override
    @Cacheable(key = "'config'")
    public EmailConfig find() {
        Optional<EmailConfig> emailConfig = emailRepository.findById(1L);
        return emailConfig.orElseGet(EmailConfig::new);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void send(EmailVo emailVo, EmailConfig emailConfig){
        if(emailConfig.getId() == null){
            throw new BadRequestException("请先配置，再操作");
        }
        try {
            //创建一个邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //设置邮件工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            //进行邮件的相关设置
            int size = emailVo.getTos().size();
            //收件人
            helper.setTo(emailVo.getTos().toArray(new String[size]));
            //主题
            helper.setSubject(emailVo.getSubject());
            //消息内容
            helper.setText(emailVo.getContent(),true);
            //发件人
            helper.setFrom(emailConfig.getFromUser(),emailConfig.getUser());
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            throw new BadRequestException(e.getMessage());
        }
    }
}
